package com.example.Controller;

import com.example.Service.ArticleService;
import com.example.Service.UserService;
import com.example.pojo.Article;
import com.example.pojo.PageBean;
import com.example.pojo.Result;
import com.example.pojo.User;
import com.example.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 文章管理
 * 用于发布文章(需要一个类别)
 * */
@RestController
@Slf4j
@RequestMapping("/cgMm")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private UserService userService;

    //1.条件查询文章列表(包含每页显示的条数)
    @GetMapping
    public Result page(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "5") Integer pageSize,
                       @RequestParam(required = false) Integer categortId,
                       @RequestParam(required = false) String state,
                       @RequestHeader(name = "token") String token){
        //获取传来的数据
        log.info("当前页{}，条目数{}，文章分类id{},文章发布状态{}",page,pageSize,categortId,state);


        //1.获取创建者id，查询该用户下数据
        Claims claims = JwtUtils.parseJWT(token);
        String phone = (String) claims.get("phone");
        User e = userService.selectUser(phone,null);
        int createId = e.getId();

        log.info("页码{}，条数{}",page,pageSize);

        PageBean pb = articleService.page(page,pageSize,categortId,state,createId);

        return Result.success(pb);
    }


    //2.发布文章
    @PostMapping
    public Result addArticle(@RequestBody @Validated Article article,@RequestHeader(name = "token") String token){

        Claims claims = JwtUtils.parseJWT(token);
        String phone = (String) claims.get("phone");

        User e = userService.selectUser(phone,null);
        //1.查询改用户并且获取创建者id,通过该id添加分类文章
        int createId = e.getId();

        articleService.addArticle(article,createId);

        return Result.success();
    }

    //3.根据文章id删除文章
    @DeleteMapping("/{id}")
    public Result deleteArticle(@PathVariable Integer id){//路径参数

        articleService.delete(id);

        return Result.success();
    }




}
